/**
 * 部分移动端 页面使用rem单位兼容
 * 使用后设计稿 1px 等于页面 1rem
 */
export function useMobileCssScale() {
  const backupRem = ref('')
  const appMinWidth = ref('')

  const compatibleWithMobileDevice = () => {
    const rootElement = document.querySelector('html') as HTMLElement
    backupRem.value = rootElement.style.getPropertyValue('font-size')

    const appElement = document.querySelector('#app') as HTMLElement
    appMinWidth.value = appElement.style.getPropertyValue('min-width')
    appElement.style.setProperty('min-width', 'unset')


    const designWidth = 750 // px 设计稿宽度
    const scale = 1 / window.devicePixelRatio // 缩放比例

    const appendMeta = document.createElement('meta')
    appendMeta.setAttribute('id', 'append-meta')
    appendMeta.setAttribute('name', 'viewport')
    appendMeta.setAttribute('content', `width=device-width,initial-scale=${scale} user-scalable=no`)
    const headElement = document.querySelector('head') as HTMLElement
    headElement.appendChild(appendMeta)

    rootElement.style.setProperty('font-size', (window.innerWidth / designWidth)  + 'px')
  }

// 还原
  const restoreMobileDeviceCompatible = () => {
    // 移除meta
    document.removeChild(document.querySelector('#append-meta') as HTMLElement)
    // 恢复font-size
    const rootElement = document.querySelector('html') as HTMLElement
    rootElement.style.setProperty('font-size', backupRem.value)
    // 恢复#app 样式
    const appElement = document.querySelector('#app') as HTMLElement
    appElement.style.setProperty('min-width', appMinWidth.value)
  }

  onBeforeMount(() => {
    compatibleWithMobileDevice()
  })

  onBeforeUnmount(() => {
    restoreMobileDeviceCompatible()
  })
}
